package com.example.stag;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;

@WebServlet("/userRegistration")
public class UserRegistrationServlet extends HttpServlet {

    @Override
    public void init() {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String telphone = req.getParameter("telphone");
            String sex = req.getParameter("sex");
            String usertype = req.getParameter("usertype");

            PrintWriter writer = resp.getWriter();
            ResultSet resultSet = UserSQLOperation.searchByUsername(username);
            // 循环遍历判断， 若有匹配则已存在
            while (resultSet.next()) {
                if (resultSet.getString("usertype").equals(usertype)) {
                    writer.println("existed");
                    return;
                }
            }
            UserSQLOperation.insertUser(username, password, telphone, sex, usertype);
            writer.println("OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
